from custom.handlers.basehandler import BaseRequestHandler
from models.tables import MusicModel
from utils.qq_music import get_song_key, download_file, get_lyric


class IndexHandler(BaseRequestHandler):
    def get(self, *args, **kwargs):
        need_commit = False
        song_mid = self.get_argument('song_mid', '')
        print('song_mid', song_mid)
        if not song_mid:
            self.write('参数错误')
            self.finish()
            return
        music = self.db.query(MusicModel).filter_by(song_mid=song_mid).first()
        print('music.lyric', music.lyric)
        if music is None:
            self.write('参数错误')
            self.finish()
            return
        if not music.lyric:
            lyric = get_lyric(music.song_id, music.song_mid)
            music.lyric = lyric
            need_commit = True
        if not music.song_url:
            song_url = get_song_key(song_mid)
            if song_url == '':
                self.write('获取song key 错误')
                self.finish()
                return
            try:
                song_file = download_file('audio', song_url)
            except Exception:
                song_file = None
            if song_file is None:
                self.write('获取song key 错误')
                self.finish()
                return
            music.song_url = song_url
            music.my_song_url = song_file.get('server_path', '')
            need_commit = True

        if need_commit:
            self.db.commit()
        self.render('music/index.html', music=music)

